import datetime
import random
import pygame
import tkinter as tk

# --------------sittings-------------- #
from lib.sittings import SCREENSIZE
from lib.sittings import CAPTION
from lib.sittings import BACKGROUND_COLOR
from lib.sittings import START_TILE
from lib.sittings import BLOCK_SPAWN_RATE
from lib.sittings import SCORE_POS
from lib.sittings import SCORE_COLOR
from lib.sittings import SCORE_PREFIX
from lib.sittings import FPS
from lib.sittings import SCREENRECT
from lib.sittings import START_SEGMENTS
from lib.sittings import info
from lib.sittings import openSnake_Dict
from lib import sittings

# ----------- game objects ----------- #

from lib.Snake_Body.snake_head import Snake_Head
from lib.Event.block import Block
from lib.Function import NumBox
from lib.Function.NumBox import clean
from lib.Event.food import makefood
from lib.Test_automatically.OpenSnake import openSnake
from lib.Action.die import head_tail_pos, head_blocks
from lib.Action.go import go
from lib.Event.die import die


# -------------- game logic ------------ #

def main():
    info("*" * 20 + "New Game" + "*" * 20)
    pot, num = openSnake_Dict["pot"], openSnake_Dict["num"]
    info(f"pot: {pot}")
    if pot is True:
        info(f"Open Snake to {num}")
    pygame.init()
    screen = pygame.display.set_mode(SCREENSIZE)
    pygame.display.set_caption(CAPTION)
    bg = pygame.Surface(SCREENSIZE).convert()
    bg.fill(BACKGROUND_COLOR)
    screen.blit(bg, (0, 0))

    snakegroup = pygame.sprite.Group()
    snakeheadgroup = pygame.sprite.Group()
    foodgroup = pygame.sprite.Group()
    blockgroup = pygame.sprite.Group()
    takenupgroup = pygame.sprite.Group()
    all = pygame.sprite.RenderUpdates()

    snake = Snake_Head(START_TILE, 'right', [snakegroup, all, takenupgroup])
    snakeheadgroup.add(snake)
    for index in range(START_SEGMENTS):
        snake.add_segment()

    currentfood = 'no food'

    # $$$方块个数$$$
    block_frame = 0

    # $$$分数 $$$
    currentscore = 0

    pygame.display.flip()

    # mainloop
    quit = False
    clock = pygame.time.Clock()

    # --------close---------- #
    def close():
        pygame.quit()
        # b.pack_forget()

    if sittings.start_button is None:
        sittings.start_button = tk.Button(root, text="结束游戏", command=close)
        sittings.start_button.pack()

    while not quit:
        # 自动搜索食物
        if pot is True:
            run_ = openSnake(num, snakeheadgroup, foodgroup, currentscore)
            if run_:
                info(f"* :game over:  [{datetime.datetime.now()}] 任务完成...")
                quit = lose = True
        # events
        if pot is not True:
            quit, lose = go(snake)

        # clearing
        all.clear(screen, bg)

        # updates
        all.update()

        if currentfood == 'no food':
            currentfood = makefood(num=random.randint(openSnake_Dict["food"]["min"], openSnake_Dict["food"]["max"]), takenupgroup=takenupgroup, foodgroup=foodgroup,
                                   food_all=all)
        if pot is not True:
            quit = head_tail_pos(snakeheadgroup=snakeheadgroup,
                                 snake=snake,
                                 snakegroup=snakegroup,
                                 currentscore=currentscore,
                                 screen=screen,
                                 die=die)
        if quit:
            break
        # head -> food
        col = pygame.sprite.groupcollide(snakeheadgroup, foodgroup, False, True)
        for head in col:
            info(f"[{datetime.datetime.now()}] eat food")
            for tail in col[head]:
                currentfood = 'no food'
                snake.add_segment()
                currentscore += 1
                info(f"[{datetime.datetime.now()}] currentscore({currentscore})++")
                sittings.MOVE_RATE += sittings.DIFFICULTY_INCREASE_RATE
                block_frame += 1
                if block_frame >= BLOCK_SPAWN_RATE:
                    block_frame = 0
                    b = Block(takenupgroup)
                    blockgroup.add(b)
                    takenupgroup.add(b)
                    all.add(b)
                    info(f"[{datetime.datetime.now()}] block_frame++")
                info("#" * 25 + currentfood + "#" * 25)
        # head -> blocks
        if pot is not True:
            quit = head_blocks(snakeheadgroup=snakeheadgroup,
                               blockgroup=blockgroup,
                               currentscore=currentscore,
                               screen=screen,
                               die=die)
        if quit:
            break
        # score
        d = screen.blit(bg, SCORE_POS, pygame.Rect(SCORE_POS, (50, 100)))
        f = pygame.font.Font(None, 12)
        scoreimage = f.render(SCORE_PREFIX + str(currentscore), True, SCORE_COLOR)
        d2 = screen.blit(scoreimage, SCORE_POS)

        # drawing
        dirty = all.draw(screen)
        dirty.append(d)
        dirty.append(d2)

        # updating
        pygame.display.update(dirty)

        # waiting
        clock.tick(FPS)

    # game over
    if quit is not True and lose is True:
        die(currentscore, screen)


if __name__ == "__main__":
    print("""
    
////////////////////////////////////////////////////////////////////
//                          _ooOoo_                                //
//                         o8888888o                               //
//                         88" . "88                               //
//                         (| ^_^ |)                               //
//                         O\  =  /O                               //
//                      ____/`---'\____                            //
//                    .'  \\|     |//  `.                           //
//                   /  \\|||  :  |||//  \                          //
//                  /  _||||| -:- |||||-  \                        //
//                  |   | \\\  -  /// |   |                         //
//                  | \_|  ''\---/''  |   |                        //
//                  \  .-\__  `-`  ___/-. /                        //
//                ___`. .'  /--.--\  `. . ___                      //
//              ."" '<  `.___\_<|>_/___.'  >'"".                   //
//            | | :  `- \`.;`\ _ /`;.`/ - ` : | |                  //
//            \  \ `-.   \_ __\ /__ _/   .-` /  /                  //
//      ========`-.____`-.___\_____/___.-`____.-'========          //
//                           `=---='                               //
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^         //
//         佛祖保佑       永无BUG     永不修改                        //
////////////////////////////////////////////////////////////////////
                    佛曰:
                    写字楼里写字间，写字间里程序员；
                    程序人员写程序，又拿程序换酒钱。
                    酒醒只在网上坐，酒醉还来网下眠；
                    酒醉酒醒日复日，网上网下年复年。
                    但愿老死电脑间，不愿鞠躬老板前；
                    奔驰宝马贵者趣，公交自行程序员。
                    别人笑我忒疯癫，我笑自己命太贱；
                    不见满街漂亮妹，哪个归得程序员？


    """)
    # 创建一个 Tkinter 窗口
    root = tk.Tk()
    root.title("选择功能")

    # 创建一个标签
    label = tk.Label(root, text="请选择功能:")
    label.pack()

    # 创建查看战绩按钮
    scores_button1 = tk.Button(root, text="查看战绩", command=NumBox.show)
    scores_button1.pack()

    # 创建开始游戏按钮
    start_button2 = tk.Button(root, text="开始游戏", command=main)
    start_button2.pack()

    start_button3 = tk.Button(root, text="清除所有战绩", command=clean)
    start_button3.pack()

    # 运行 Tkinter 事件循环
    root.mainloop()
